package org.easydev.wechat.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <Description> cookie工具类<br>
 * 
 * @author jian<br>
 */
public class CookieUtil {

    /**
     * Description: 新增cookie<br>
     * 
     * @param name <br>
     * @param value <br>
     * @param response <br>
     */
    public static void addCookie(String name, String value, HttpServletResponse response) {
        Cookie cookies = new Cookie(name, value);
        cookies.setPath("/");
        cookies.setMaxAge(7 * 24 * 60 * 60);
        response.addCookie(cookies);
    }

    public static String getCookieValue(String cookieName, HttpServletRequest request) {
        if (cookieName != null) {
            Cookie cookie = getCookie(cookieName, request);
            if (cookie != null) {
                return cookie.getValue();
            }
        }
        return "";
    }

    public static Cookie getCookie(String cookieName, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                cookie = cookies[i];
                if (cookie.getName().equals(cookieName)) {
                    return cookie;
                }
            }
        }
        return cookie;
    }

    public static boolean deleteCookie(String cookieName, HttpServletRequest request, HttpServletResponse response) {
        if (cookieName != null) {
            Cookie cookie = getCookie(cookieName, request);
            if (cookie != null) {
                cookie.setMaxAge(0);// 如果0，就说明立即删除
                cookie.setPath("/");// 不要漏掉
                response.addCookie(cookie);
                return true;
            }
        }
        return false;
    }

}